package com.sita.bluetactivity;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.sita.bluetactivity.Base.BaseActivity;
import com.sita.bluetactivity.Base.BaseApplication;
import com.sita.bluetactivity.Base.BaseValue;
import com.sita.bluetactivity.Base.CheckPermissionsActivity;
import com.sita.bluetactivity.Base.SpUtils;

import com.sita.bluetactivity.Base.ToastUtils;
import com.sita.bluetactivity.MineFragment.SendBinderEvent;
import com.sita.bluetactivity.NewBlueTooth.BtService;
import com.sita.bluetactivity.VehicleFragment.VehicleFragment;
import com.sita.bluetactivity.MineFragment.MineSettingFragment;
import com.sita.bluetactivity.SafeFragment.VehicleSafeFragment;
import com.sita.bluetactivity.TripFragment.VehicleTripFragment;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.service.XGPushService;


import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import retrofit.http.Header;

/**
 * Created by Jason on 2016/9/21.
 */
public class MainActivity extends BaseActivity {
    private RadioGroup grop;
    private VehicleFragment vehiclefragment;
    private VehicleTripFragment vehicleTripFragment;
    private VehicleSafeFragment vehicleSafeFragment;
    private MineSettingFragment mineSettingFragment;
    private TextView headTx;
    private ImageView head_img;
    private boolean mScanning = true;
    private static Handler handler = new Handler();
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private BtService.BtBinder btBinder;
    private Intent intentService;
    private BroadBtCast broadBtCast = new BroadBtCast();
    private  String deviceName;
    private BluetoothDevice bluetoothDevice;
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if (device.getName()!=null&&device.getName().equals(deviceName)){
                bluetoothDevice = device;
            }
        }
    };



    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            btBinder = (BtService.BtBinder) service;
            //给主页发送Binder对象
            EventBus.getDefault().post(btBinder);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            btBinder =null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().setFormat(PixelFormat.TRANSLUCENT);
        headTx = (TextView) findViewById(R.id.head_tx);
        intView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(R.color.main_bg);//通知栏所需颜色
        intentService = new Intent(this,BtService.class);
        bindService(intentService,connection,BIND_AUTO_CREATE);
        initXingGe();
        //初始化蓝牙适配器
        bluetoothAdapter = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();



    }
    private void initXingGe(){
        String accountId = SpUtils.getString("AccountId",null,BaseApplication.getContext());
        Context context = BaseApplication.getContext();
        if (accountId!=null){
            XGPushManager.registerPush(context,"ss" , new XGIOperateCallback() {
                @Override
                public void onSuccess(Object o, int i) {
                    Log.d("TPush", "注册成功，设备token为：" + o);

                }

                @Override
                public void onFail(Object o, int i, String s) {
                    Log.d("TPush", "注册失败，错误码：" + i + ",错误信息：" + s);
                }
            });
        }

    }


    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }
    @Override
    protected void onResume() {
        super.onResume();
        // 蓝牙开闭状态接收器
    }

    @Override
    protected int getId() {
        return R.layout.activity_main;
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(broadBtCast ,intentFilter);
        deviceName = SpUtils.getString("DeviceID",null,BaseApplication.getContext());

    }
    private void intView(){
        grop = (RadioGroup) findViewById(R.id.main_grop);
        head_img = (ImageView) findViewById(R.id.head_logo);
        head_img.setVisibility(View.VISIBLE);
        grop.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                FragmentManager manager = getSupportFragmentManager();
                FragmentTransaction transcation = manager.beginTransaction();
                hidtFragment(transcation);
                switch (checkedId){
                    case R.id.vehicle:
                      //  headTx.setText("新大洲内侧");
                        if (vehiclefragment==null){
                            vehiclefragment = new VehicleFragment();
                            transcation.add(R.id.replace_view,vehiclefragment);
                        }
                        else {
                            transcation.show(vehiclefragment);
                        }
                        break;
                    case R.id.trip:
                       // headTx.setText("新大洲内侧");
                        if (vehicleTripFragment==null){
                            vehicleTripFragment = new VehicleTripFragment();
                            transcation.add(R.id.replace_view,vehicleTripFragment);
                        }
                        else {
                            transcation.show(vehicleTripFragment);
                        }
                        break;
                    case R.id.safe:
                       // headTx.setText("新大洲内侧");
                        if (vehicleSafeFragment==null){
                            vehicleSafeFragment = new VehicleSafeFragment();
                           transcation.add(R.id.replace_view,vehicleSafeFragment);
                        }
                        else {
                            transcation.show(vehicleSafeFragment);
                        }
                        break;
                    case R.id.mine:
                      //  headTx.setText("新大洲内侧");
                        if (mineSettingFragment==null){
                          mineSettingFragment = new   MineSettingFragment();
                            transcation.add(R.id.replace_view,mineSettingFragment);
                        }
                        else {
                            transcation.show(mineSettingFragment);
                        }
                        break;
               }
                transcation.commit();
            }
       });
        grop.check(R.id.vehicle);
    }
    private void hidtFragment(FragmentTransaction fragmentTransaction){
        if (vehiclefragment != null){
            fragmentTransaction.hide(vehiclefragment);
        }
        if (vehicleTripFragment != null){
            fragmentTransaction.hide(vehicleTripFragment);
        }
        if (vehicleSafeFragment != null){
            fragmentTransaction.hide(vehicleSafeFragment);
        }
        if (mineSettingFragment != null){
            fragmentTransaction.hide(mineSettingFragment);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseValue.BtIsConnection =  false;//退出程序以后连接断开
        unbindService(connection);

    }
    //接到设备通知以后发送Bindder对象

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(broadBtCast);
    }

    public static void getMainIntent(Context context){
    Intent intent = new Intent(context, MainActivity.class);
    context.startActivity(intent);

}
class BroadBtCast extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)){
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                    BluetoothAdapter.ERROR);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    Log.d("aaa", "STATE_OFF 手机蓝牙关闭");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d("aaa", "STATE_TURNING_OFF 手机蓝牙正在关闭");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.d("aaa", "STATE_ON 手机蓝牙开启");
                    //蓝牙开启之后进行扫描连接
                    scanBtDevice(true);

                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.d("aaa", "STATE_TURNING_ON 手机蓝牙正在开启");
                    break;
            }
        }
    }
}
    private void scanBtDevice(boolean state){
        if (state){
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    bluetoothAdapter.stopLeScan(mLeScanCallback);
                    if (bluetoothDevice!=null){
                        BaseValue.isFirstConnection = false;
                        btBinder.connection(bluetoothDevice);
                    }
                }
            },5000);
            mScanning = true;
            bluetoothAdapter.startLeScan(mLeScanCallback);
        }
        else {
            mScanning = false;
            bluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }

}
